package com.yayun.merchant.service.impl;

import java.util.List;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yayun.merchant.domain.OmsOrder;
import com.yayun.merchant.domain.OmsOrderItem;
import com.yayun.merchant.domain.OmsOrderOperateHistory;
import com.yayun.merchant.domain.OmsOrderDeliveryHistory;
import com.yayun.merchant.mapper.OmsOrderMapper;
import com.yayun.merchant.mapper.OmsOrderItemMapper;
import com.yayun.merchant.mapper.OmsOrderOperateHistoryMapper;
import com.yayun.merchant.mapper.OmsOrderDeliveryHistoryMapper;
import com.yayun.merchant.service.IOmsOrderService;
import com.yayun.common.utils.SecurityUtils;
import com.yayun.common.utils.StringUtils;
import com.yayun.common.exception.ServiceException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ThreadLocalRandom;

@Service
public class OmsOrderServiceImpl implements IOmsOrderService {
    @Autowired
    private OmsOrderMapper orderMapper;

    @Autowired
    private OmsOrderItemMapper orderItemMapper;

    @Autowired
    private OmsOrderOperateHistoryMapper orderOperateHistoryMapper;

    @Autowired
    private OmsOrderDeliveryHistoryMapper orderDeliveryHistoryMapper;

    @Override
    public List<OmsOrder> selectOrderList(OmsOrder order) {
        // 非管理员只能查看自己的订单
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            order.setUserId(SecurityUtils.getUserId());
        }
        return orderMapper.selectOrderList(order);
    }

    @Override
    public OmsOrder selectOrderById(Long id) {
        return orderMapper.selectOrderById(id);
    }

    @Override
    @Transactional
    public OmsOrder createOrder(OmsOrder order) {
        // 数据验证
        if (order.getItems() == null || order.getItems().isEmpty()) {
            throw new ServiceException("订单商品不能为空");
        }
        
        // 设置用户信息
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        if (userId == null || StringUtils.isEmpty(username)) {
            throw new ServiceException("用户未登录");
        }
        order.setUserId(userId);
        order.setUsername(username);
        
        // 验证收货人信息
        if (StringUtils.isEmpty(order.getReceiverName()) || 
            StringUtils.isEmpty(order.getReceiverPhone()) ||
            StringUtils.isEmpty(order.getReceiverDetailAddress())) {
            throw new ServiceException("收货人信息不完整");
        }
        
        // 生成订单ID
        long timestamp = System.currentTimeMillis();
        int random = ThreadLocalRandom.current().nextInt(1000, 9999);
        // 使用时间戳后8位 + 4位随机数作为订单ID，避免超出Long范围
        long orderId = Long.parseLong(String.valueOf(timestamp).substring(5) + String.format("%04d", random));
        order.setId(orderId);
        
        // 生成订单编号
        order.setOrderSn(generateOrderSn());
        
        // 设置订单基本信息
        order.setCreateTime(new Date());
        order.setCreateBy(userId);
        order.setStatus(0); // 待付款状态
        order.setDeleteStatus(false);
        order.setConfirmStatus(0);
        
        // 保存订单
        orderMapper.insertOrder(order);
        
        // 保存订单商品信息
        for (OmsOrderItem item : order.getItems()) {
            item.setId(generateItemId());
            item.setOrderId(orderId);
            item.setOrderSn(order.getOrderSn());
            item.setCreateTime(new Date());
            item.setCreateBy(userId);
            orderItemMapper.insertOrderItem(item);
        }
        
        // 记录订单操作历史
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(orderId);
        history.setOrderSn(order.getOrderSn());
        history.setOperateMan(username);
        history.setOrderStatus(0);
        history.setNote("创建订单");
        history.setCreateTime(new Date());
        history.setCreateBy(userId);
        orderOperateHistoryMapper.insertOrderOperateHistory(history);
        
        // 返回完整的订单对象，包含ID
        return order;
    }

    // 生成订单编号
    private String generateOrderSn() {
        LocalDateTime now = LocalDateTime.now();
        String timestamp = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        int random = ThreadLocalRandom.current().nextInt(1000, 9999);
        return timestamp + random;
    }

    // 生成订单项ID
    private Long generateItemId() {
        long timestamp = System.currentTimeMillis();
        int random = ThreadLocalRandom.current().nextInt(1000, 9999);
        return Long.parseLong(timestamp + String.format("%04d", random));
    }

    @Override
    public int updateOrder(OmsOrder order) {
        order.setUpdateBy(SecurityUtils.getUserId());
        return orderMapper.updateOrder(order);
    }

    @Override
    public int updateOrderStatus(Long orderId, Integer status) {
        return orderMapper.updateOrderStatus(orderId, status);
    }

    @Override
    public int deleteOrderById(Long id) {
        return orderMapper.deleteOrderById(id);
    }

    @Override
    public int deleteOrderByIds(Long[] ids) {
        return orderMapper.deleteOrderByIds(ids);
    }

    @Override
    @Transactional
    public int payOrder(Long orderId, Integer payType) {
        // 查询订单
        OmsOrder order = orderMapper.selectOrderById(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        
        // 验证订单状态
        if (order.getStatus() != 0) {
            throw new ServiceException("订单状态不正确");
        }
        
        // 更新订单状态
        order.setStatus(1); // 待发货
        order.setPayType(payType);
        order.setPaymentTime(new Date());
        order.setUpdateTime(new Date());
        order.setUpdateBy(SecurityUtils.getUserId());
        orderMapper.updateOrder(order);
        
        // 记录订单操作历史
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(orderId);
        history.setOrderSn(order.getOrderSn());
        history.setOperateMan(SecurityUtils.getUsername());
        history.setOrderStatus(1);
        history.setNote("支付订单");
        history.setCreateTime(new Date());
        history.setCreateBy(SecurityUtils.getUserId());
        orderOperateHistoryMapper.insertOrderOperateHistory(history);
        
        return 1;
    }

    @Override
    @Transactional
    public int deliveryOrder(Long orderId, String deliveryCompany, String deliverySn) {
        // 查询订单
        OmsOrder order = orderMapper.selectOrderById(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        
        // 验证订单状态
        if (order.getStatus() != 1) {
            throw new ServiceException("订单状态不正确");
        }
        
        // 更新订单状态
        order.setStatus(2); // 已发货
        order.setDeliveryCompany(deliveryCompany);
        order.setDeliverySn(deliverySn);
        order.setDeliveryTime(new Date());
        order.setUpdateTime(new Date());
        order.setUpdateBy(SecurityUtils.getUserId());
        orderMapper.updateOrder(order);
        
        // 记录订单操作历史
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(orderId);
        history.setOrderSn(order.getOrderSn());
        history.setOperateMan(SecurityUtils.getUsername());
        history.setOrderStatus(2);
        history.setNote("发货订单");
        history.setCreateTime(new Date());
        history.setCreateBy(SecurityUtils.getUserId());
        orderOperateHistoryMapper.insertOrderOperateHistory(history);
        
        // 记录发货历史
        OmsOrderDeliveryHistory deliveryHistory = new OmsOrderDeliveryHistory();
        deliveryHistory.setOrderId(orderId);
        deliveryHistory.setDeliveryCompany(deliveryCompany);
        deliveryHistory.setDeliverySn(deliverySn);
        deliveryHistory.setCreateTime(new Date());
        deliveryHistory.setCreateBy(SecurityUtils.getUserId());
        orderDeliveryHistoryMapper.insertOrderDeliveryHistory(deliveryHistory);
        
        return 1;
    }

    @Override
    @Transactional
    public int confirmReceiveOrder(Long orderId) {
        // 查询订单
        OmsOrder order = orderMapper.selectOrderById(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        
        // 验证订单状态
        if (order.getStatus() != 2) {
            throw new ServiceException("订单状态不正确");
        }
        
        // 更新订单状态
        order.setStatus(3); // 已完成
        order.setConfirmStatus(1);
        order.setReceiveTime(new Date());
        order.setUpdateTime(new Date());
        order.setUpdateBy(SecurityUtils.getUserId());
        orderMapper.updateOrder(order);
        
        // 记录订单操作历史
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(orderId);
        history.setOrderSn(order.getOrderSn());
        history.setOperateMan(SecurityUtils.getUsername());
        history.setOrderStatus(3);
        history.setNote("确认收货");
        history.setCreateTime(new Date());
        history.setCreateBy(SecurityUtils.getUserId());
        orderOperateHistoryMapper.insertOrderOperateHistory(history);
        
        return 1;
    }

    @Override
    @Transactional
    public int cancelOrder(Long orderId, String note) {
        // 查询订单
        OmsOrder order = orderMapper.selectOrderById(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        
        // 验证订单状态
        if (order.getStatus() != 0) {
            throw new ServiceException("订单状态不正确");
        }
        
        // 更新订单状态
        order.setStatus(4); // 已关闭
        order.setUpdateTime(new Date());
        order.setUpdateBy(SecurityUtils.getUserId());
        orderMapper.updateOrder(order);
        
        // 记录订单操作历史
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(orderId);
        history.setOrderSn(order.getOrderSn());
        history.setOperateMan(SecurityUtils.getUsername());
        history.setOrderStatus(4);
        history.setNote(note);
        history.setCreateTime(new Date());
        history.setCreateBy(SecurityUtils.getUserId());
        orderOperateHistoryMapper.insertOrderOperateHistory(history);
        
        return 1;
    }

    @Override
    @Transactional
    public int cancelOrderByOrderSn(String orderSn, String note) {
        // 查询订单
        OmsOrder order = orderMapper.selectOrderByOrderSn(orderSn);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        
        // 验证订单状态
        if (order.getStatus() != 0) {
            throw new ServiceException("订单状态不正确，只能取消待付款订单");
        }
        
        // 验证订单所属用户
        Long userId = SecurityUtils.getUserId();
        if (!userId.equals(order.getUserId())) {
            throw new ServiceException("无权操作此订单");
        }
        
        // 更新订单状态
        order.setStatus(4); // 已取消
        order.setNote(note);
        order.setUpdateTime(new Date());
        order.setUpdateBy(userId);
        orderMapper.updateOrder(order);
        
        // 记录订单操作历史
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(order.getId());
        history.setOrderSn(order.getOrderSn());
        history.setOperateMan(SecurityUtils.getUsername());
        history.setOrderStatus(4);
        history.setNote(note);
        history.setCreateTime(new Date());
        history.setCreateBy(userId);
        orderOperateHistoryMapper.insertOrderOperateHistory(history);
        
        return 1;
    }

    @Override
    @Transactional
    public int payOrderByOrderSn(String orderSn, Integer payType) {
        // 查询订单
        OmsOrder order = orderMapper.selectOrderByOrderSn(orderSn);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        
        // 验证订单状态
        if (order.getStatus() != 0) {
            throw new ServiceException("订单状态不正确");
        }
        
        // 验证订单所属用户
        Long userId = SecurityUtils.getUserId();
        if (!userId.equals(order.getUserId())) {
            throw new ServiceException("无权操作此订单");
        }
        
        // 更新订单状态
        order.setStatus(1); // 待发货
        order.setPayType(payType);
        order.setPaymentTime(new Date());
        order.setUpdateTime(new Date());
        order.setUpdateBy(userId);
        orderMapper.updateOrder(order);
        
        // 记录订单操作历史
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(order.getId());
        history.setOrderSn(order.getOrderSn());
        history.setOperateMan(SecurityUtils.getUsername());
        history.setOrderStatus(1);
        history.setNote("支付订单");
        history.setCreateTime(new Date());
        history.setCreateBy(userId);
        orderOperateHistoryMapper.insertOrderOperateHistory(history);
        
        return 1;
    }

    @Override
    public OmsOrder selectOrderByOrderSn(String orderSn) {
        OmsOrder order = orderMapper.selectOrderByOrderSn(orderSn);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        return order;
    }

    @Override
    @Transactional
    public int updateOrderNote(OmsOrder order) {
        // 查询订单
        OmsOrder existOrder = orderMapper.selectOrderById(order.getId());
        if (existOrder == null) {
            throw new ServiceException("订单不存在");
        }
        
        // 更新订单备注
        existOrder.setNote(order.getNote());
        existOrder.setUpdateTime(new Date());
        existOrder.setUpdateBy(SecurityUtils.getUserId());
        orderMapper.updateOrder(existOrder);
        
        // 记录订单操作历史
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(order.getId());
        history.setOrderSn(existOrder.getOrderSn());
        history.setOperateMan(SecurityUtils.getUsername());
        history.setOrderStatus(existOrder.getStatus());
        history.setNote("更新订单备注：" + order.getNote());
        history.setCreateTime(new Date());
        history.setCreateBy(SecurityUtils.getUserId());
        orderOperateHistoryMapper.insertOrderOperateHistory(history);
        
        return 1;
    }
} 